package com.david;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Base64;
import java.util.Calendar;
import java.util.Date;

public class JwtUtil {
    /**
     * 密钥，进服务端存储
     */
    private static String secret="ko346134h_we]rg3in_yip1!";

    /**
     *
     * @param subject
     * @param issueDate 签发时间
     * @return
     */
    public static String createToken(String subject, Date issueDate){

        Calendar c=Calendar.getInstance();
        c.setTime(issueDate);
        c.add(Calendar.DAY_OF_MONTH,20);

        String compactJws=Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(issueDate)
                .setExpiration(c.getTime())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
        return compactJws;
    }


    /**
     * 校验token
     * @param token
     * @return
     */
    public static String parseToken(String token){
        try {
            Claims claims= (Claims) Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            if (claims!=null){
                return claims.getSubject();
            }
        }catch (ExpiredJwtException e){
            e.printStackTrace();
            System.out.println("jwt过期了");
        }
        return "";
    }

    public static void main(String[] args) {
        String token = createToken("userid=1,role=admin,price=398", new Date());
        //eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyaWQ9MSxyb2xlPWFkbWluLHByaWNlPTM5OCIsImlhdCI6MTYyMzU3NzY0OCwiZXhwIjoxNjI1MzA1NjQ4fQ.ZJIp3y22Sz0lJLwUaUXoH7KyFI8JtTFZ8RFoIbJXiPnEmsn5XOv5Jy5tmMIeOqZqTkJQKz4bFIWYvF0BnKxJhw
        System.out.println(token);

        byte[] decode = Base64.getDecoder().decode("eyJhbGciOiJIUzUxMiJ9");
        System.out.println(new String(decode));

        String parseToken = parseToken("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyaWQ9MSxyb2xlPWFkbWluLHByaWNlPTM5OCIsImlhdCI6MTYyMzU3NzY0OCwiZXhwIjoxNjI1MzA1NjQ4fQ.ZJIp3y22Sz0lJLwUaUXoH7KyFI8JtTFZ8RFoIbJXiPnEmsn5XOv5Jy5tmMIeOqZqTkJQKz4bFIWYvF0BnKxJhw");
        System.out.println("parseToken"+parseToken);


    }
}
